import React, { useRef, useMemo, useState, useCallback, useEffect, memo, useContext } from 'react';

import './index.less';

import { useLocation, Link, useNavigate } from 'react-router-dom';
import { useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { StateType, globalState, headTabNavListState } from '@/store/global';

import { Tag } from 'antd';
import { IRouter, IRouterPathKeyRouter } from '@/types/router';

export interface TagsViewProps {
  routerPathKeyRouter: IRouterPathKeyRouter;
  routeItem: IRouter;
}

const TagsView = memo(({ routerPathKeyRouter, routeItem }: TagsViewProps) => {
  // const { tags, dispatch, defaultTags, routes: routeLists, allRedirects } = props;
  // const { routerPathKeyRouter, routeItem } = useContext(LayoutContext);
  console.log('tags render');
  const tagListContainer = useRef<HTMLDivElement>(null);
  const location = useLocation();
  const currentPath = location.pathname;
  const navigate = useNavigate();

  const contextMenuContainer = useRef<HTMLUListElement>(null);
  const [menuVisible, setMenuVisible] = useState(false);
  const [left, setLeft] = useState(0);
  const [top, setTop] = useState(0);
  const [currentTag, setCurrentTag] = useState<IRouter>();

  const setGlobal = useSetRecoilState(globalState);
  const tags = useRecoilValue(headTabNavListState);

  // 过滤固定的tag
  const findAffixTags = (routes: IRouter[], tag: IRouter[] = []) => {
    routes.forEach((item) => {
      const { children, meta } = item;
      if (meta?.isAffix === true) {
        tag.push(item);
      }
      if (children && children.length > 0) {
        findAffixTags(children, tag);
      }
    });
    return tag;
  };
  // 鼠标滚动
  const handleScroll = (e: any) => {
    e.preventDefault();
    const eventDelta = e.wheelDelta || -e.deltaY * 40;
    const tagListWrapper = tagListContainer.current;
    if (!tagListWrapper) return;
    tagListWrapper.scrollLeft += eventDelta / 4;
  };
  // 设置state global navList
  const setGlobalHeadTabNavList = (val: (currVal: StateType) => IRouter[]) => {
    setGlobal((preVal) => {
      const navList = val(preVal);
      return {
        ...preVal,
        headTabNavList: [...navList],
      };
    });
  };

  // 设置TabNav
  const setTabNav = (location: any, routeItem: IRouter): void => {
    // routeItem 不存在说明不在Layout route内
    if (!routeItem || location.pathname !== routeItem.path || (routeItem.children && routeItem.children?.length > 0)) {
      return;
    }
    let index = 0;

    setGlobalHeadTabNavList((val) => {
      // 数组里是否已经存在当前route规则，不存在下标为-1
      index = val.headTabNavList.findIndex((item) => item.path === routeItem.path);
      if (index < 0) {
        index = val.headTabNavList.length;
        return [...val.headTabNavList, routeItem];
      }
      return val.headTabNavList;
    });
  };

  /**
   * @description: 初始化Tags
   */
  const initTags = () => {
    setGlobalHeadTabNavList(() => findAffixTags(routerPathKeyRouter.router));
  };

  useEffect(() => {
    initTags();
  }, []);

  useEffect(() => {
    setTabNav(location, routeItem);
  }, [routeItem, location]);

  useEffect(() => {
    // 在这里处理状态值的更新
    if (tags.length > 0) moveToTarget(routeItem.path);
  }, [tags]);

  useEffect(() => {
    // 在组件挂载后执行副作用操作
    document.addEventListener('click', handleOutSideClick);
    tagListContainer.current?.addEventListener('wheel', handleScroll, { passive: false });
    // 在组件卸载前执行清理操作
    return () => {
      document.removeEventListener('click', handleOutSideClick);
      tagListContainer.current?.removeEventListener('wheel', handleScroll);
    };
  }, []);
  // 点击空白处关闭
  const handleOutSideClick = (e: any) => {
    if (contextMenuContainer.current && !contextMenuContainer.current.contains(e.target)) {
      setMenuVisible(false);
    }
  };

  // 关闭
  const handleClose = async (e: React.MouseEvent<HTMLElement, MouseEvent>, tag: IRouter) => {
    e.preventDefault();
    const { path } = tag;
    const navList = [...tags];
    const index = navList.findIndex((v) => v.path === path);
    if (index !== -1) {
      navList.splice(index, 1);
      updatePage(path);
      setGlobalHeadTabNavList(() => navList);
    }
  };
  // 点击
  const handleClick = (path: string) => {
    navigate(path);
  };
  /**
   * @description: 滚动到当前tag
   * @param {*} currentTag
   */
  const moveToTarget = (currentTag: string) => {
    const $container = tagListContainer.current!;
    const $containerWidth = $container.offsetWidth;

    let firstTag: IRouter | null = null;
    let lastTag: IRouter | null = null;
    // const tags = global.headTabNavList;
    // find first tag and last tag
    if (tags.length > 0) {
      firstTag = tags[0];
      lastTag = tags[tags.length - 1];
    }

    if (firstTag?.path === currentTag) {
      $container.scrollLeft = 0;
    } else if (lastTag?.path === currentTag) {
      $container.scrollLeft = $container.scrollWidth - $containerWidth;
    } else {
      const tagListDom = document.getElementsByClassName('tags-view-item');

      const currentIndex = tags.findIndex((item) => item.path === currentTag);
      let prevTag: Element | null = null;
      let nextTag: Element | null = null;

      Object.keys(tagListDom).forEach((k: any) => {
        if (k !== 'length' && Object.hasOwnProperty.call(tagListDom, k)) {
          console.log(currentIndex);
          if ((tagListDom[k] as any).dataset.path === tags[currentIndex - 1].path) {
            prevTag = tagListDom[k];
          }
          if ((tagListDom[k] as any).dataset.path === tags[currentIndex + 1].path) {
            nextTag = tagListDom[k];
          }
        }
      });
      console.log(nextTag);
      // the tag's offsetLeft after of nextTag
      const afterNextTagOffsetLeft = (nextTag as any).offsetLeft + (nextTag as any).offsetWidth + 4;

      // the tag's offsetLeft before of prevTag
      const beforePrevTagOffsetLeft = (prevTag as any).offsetLeft - 4;
      if (afterNextTagOffsetLeft > $container.scrollLeft + $containerWidth) {
        $container.scrollLeft = afterNextTagOffsetLeft - $containerWidth;
      } else if (beforePrevTagOffsetLeft < $container.scrollLeft) {
        $container.scrollLeft = beforePrevTagOffsetLeft;
      }
    }
  };
  // 右键打开菜单
  const openContextMenu = (e: React.MouseEvent<HTMLElement, MouseEvent>, tag: IRouter) => {
    e.preventDefault();
    const menuMinWidth = 105;
    const clickX = e.clientX;
    const clickY = e.clientY; // 事件发生时鼠标的Y坐标
    const el = tagListContainer.current;
    const offsetLeft = el!.getBoundingClientRect().left; // container margin left
    const { offsetWidth } = el!; // container width
    const maxLeft = offsetWidth - menuMinWidth; // left boundary
    const marginRight = clickX - offsetLeft + 15; // 15: margin right

    if (marginRight > maxLeft) {
      setLeft(maxLeft);
    } else {
      setLeft(marginRight);
    }
    setTop(clickY);
    setMenuVisible(true);
    setCurrentTag(tag);
  };
  // 关闭右键菜单
  const closeContextMenu = () => setMenuVisible(false);
  // 关闭其他
  const handleCloseOtherTags = () => {
    // 有关闭回调的和当前打开的和首页无法关闭
    const navList = tags.filter(
      (item) =>
        (item.meta?.tabNavCloseBefore && typeof item.meta.tabNavCloseBefore === 'function') ||
        item.path === currentTag?.path ||
        item.meta?.isAffix,
    );
    setGlobalHeadTabNavList(() => [...navList]);
    navigate(currentTag?.path as string);
    closeContextMenu();
  };
  const handleCloseAllTags = () => {
    // 有关闭回调的和当前打开的和首页无法关闭
    const navList = tags.filter(
      (item) =>
        (item.meta?.tabNavCloseBefore && typeof item.meta.tabNavCloseBefore === 'function') || item.meta?.isAffix,
    );
    setGlobalHeadTabNavList(() => [...navList]);
    navigate(navList[0].path);
    closeContextMenu();
  };
  // 关闭页面更新
  const updatePage = (path: string) => {
    const len = tags.length;
    if (len <= 0) return;
    const lastPath = tags[len - 1].path;

    let goPath;
    // 如果删除的是当前页面，则删除之后，最后一个tag 切换成激活页面
    if (path === currentPath) {
      // 如果关闭的是最后一个tag
      if (lastPath === currentPath) {
        if (len >= 2) {
          goPath = tags[len - 2].path;
        } else {
          goPath = tags[0].path;
        }
      } else {
        goPath = tags[len - 1].path;
      }
    } else {
      // 如果删除的是其他页面，则删除之后，激活页面不变
      goPath = currentPath;
    }
    navigate(goPath);
  };

  return (
    <>
      <div className='tagsViewContainer' ref={tagListContainer}>
        <ul className={'tagsWrap'}>
          {tags.length > 0 &&
            tags.map((tag) => (
              <li key={tag.path} className='tags-view-item' data-path={tag.path}>
                <Tag
                  onClose={(e) => handleClose(e, tag)}
                  closable={tag.meta?.isAffix !== true}
                  onClick={() => handleClick(tag.path)}
                  onContextMenu={(e) => openContextMenu(e, tag)}
                  color={currentPath === tag.path ? '#55acee' : ''}
                >
                  <Link to={tag.path}>
                    {currentPath === tag.path ? <span className={'active'} /> : null}
                    {tag.meta?.title}
                  </Link>
                </Tag>
              </li>
            ))}
        </ul>
      </div>

      {menuVisible ? (
        <ul className={'contextmenu'} style={{ left: `${left}px`, top: `${top}px` }} ref={contextMenuContainer}>
          <li onClick={handleCloseOtherTags}>关闭其他</li>
          <li onClick={handleCloseAllTags}>关闭所有</li>
        </ul>
      ) : null}
    </>
  );
});

export default TagsView;
